package org.example.c_0_011;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class T_ForkJoinPool {
    static class RecursionTask extends RecursiveTask<Long>{
        private Integer start;
        private Integer end;
        private static final Integer MAX=1000;
        public RecursionTask(Integer start, Integer end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Long compute() {
            if (end-start<=MAX){
                long sum = 0;
                for (Integer i = start; i < end; i++) {
                    sum+=i;
                }
                return sum;
            }
            int middle = (start+end)/2;
            RecursionTask recursionTask1 = new RecursionTask(start, middle);
            RecursionTask recursionTask2 = new RecursionTask(middle, end);
            recursionTask1.fork();
            recursionTask2.fork();
            return recursionTask1.join()+recursionTask2.join();
        }
    }

    public static void main(String[] args) {
        long sum = 0;
        for (Integer i = 0; i < 10000; i++) {
            sum+=i;
        }
        System.out.println(sum);

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        RecursionTask recursionTask = new RecursionTask(0, 10000); // 不包括10000
        forkJoinPool.execute(recursionTask);
        Long join = recursionTask.join();
        System.out.println(join);
    }
}
